

# Create your views here.
from django.db import connections
from envs.models import DbInfo


class DbUtil:

    def __init__(self,dbInfo:DbInfo):
        newDatabase = {}
        newDatabase["id"] = dbInfo.db_instance
        newDatabase['ENGINE'] = dbInfo.db_engine
        newDatabase['NAME'] = dbInfo.db_instance
        newDatabase['USER'] = dbInfo.db_user
        newDatabase['PASSWORD'] = dbInfo.db_password
        newDatabase['HOST'] = dbInfo.db_address
        newDatabase['PORT'] = dbInfo.db_port
        connections.databases[dbInfo.db_instance] = newDatabase
        self.conn=connections[dbInfo.db_instance]

    def execu_sql(self,sql:str):
        cursor = self.conn.cursor()
        # 插入,更新，删除
        result=cursor.execute(sql)
        self.conn.commit()
        cursor.close()
        return [{"isSucess":result}]

    def get_all(self,sql:str):
        cursor = self.conn.cursor()
        cursor.execute(sql)
        dict_result =[dict(zip([d[0] for d in cursor.description], row)) for row in cursor.fetchall()]
        self.conn.commit()
        cursor.close()
        return dict_result

    def __del__(self):
        self.conn.close()





